﻿using DotNetty.Handlers.Logging;
using DotNetty.Transport.Bootstrapping;
using DotNetty.Transport.Channels;
using DotNetty.Transport.Channels.Sockets;
using Microsoft.Extensions.Configuration;
using PSAMMatrixCloud.Common;
using PSAMMatrixCloud.Model;
using System;
using System.Configuration;
using System.IO;
using System.Threading;
using System.Threading.Tasks;

namespace PSAMMatrixCloud.TransferSecret.LaneMutual
{
    public class LaneServer 
    {
        public static async Task RunAsync()
        {
            Environment.SetEnvironmentVariable("io.netty.allocator.numDirectArenas", "0");
            var bossGroup = new MultithreadEventLoopGroup(1);
            var workerGroup = new MultithreadEventLoopGroup();
            int listenPort = 58001;//监听端口

            try
            {
                if (!string.IsNullOrWhiteSpace(PSAMSeetings.ListenPort))
                {
                    listenPort = int.Parse(PSAMSeetings.ListenPort);
                }
            }
            catch
            {
                listenPort = 58001;
            }
            LaneChannelAlive.Start();
            try
            {
                var bootstrap = new ServerBootstrap();
                bootstrap.Group(bossGroup, workerGroup)
                         .Channel<TcpServerSocketChannel>()
                         .Option(ChannelOption.SoBacklog, 1024 * 1024)
                         .Option(ChannelOption.WriteBufferHighWaterMark, 64 * 1024)
                         .Option(ChannelOption.WriteBufferLowWaterMark, 32 * 1024)
                         .Option(ChannelOption.TcpNodelay, true)
                         .ChildOption(ChannelOption.SoKeepalive, true)
                         .ChildHandler(new ActionChannelInitializer<ISocketChannel>(channel =>
                         {
                             IChannelPipeline pipeline = channel.Pipeline;
                             pipeline.AddLast(new MessageEncoder(), new MessageDecoder(), new LaneServerHandler());
                         }));

                await bootstrap.BindAsync(listenPort);
               
                LogHelper.Info($"启动云端秘钥接入服务,监听端口:{listenPort}");
            }
            catch (Exception ex)
            {
                //记录错误日志
                LogHelper.Error("对接设备服务异常", ex);
                //关闭服务
                Task.WaitAll(bossGroup.ShutdownGracefullyAsync(), workerGroup.ShutdownGracefullyAsync());
            }
        }
    }
}